#include "stdafx.h"
#include "SceneLua.h"
#include "SceneManagerLua.h"


namespace SceneManagerLua
{

bool push(lua_State* L, ISceneManager* pSceneMgr)
{
	ISceneManager** pp = (ISceneManager**)lua_newuserdata(L, sizeof(ISceneManager*));
	*pp = pSceneMgr;
	luaL_getmetatable(L, "woe.scenemgr");
	if (lua_istable(L, -1))
	{
		lua_setmetatable(L, -2);
		return true;
	}
	else
	{
		LOG_ERROR("Failed to push IScene to lua, metatable not found!");
		return false;
	}
}

ISceneManager* getUserData(lua_State* L)
{
	ISceneManager**pp = (ISceneManager**)luaL_checkudata(L, 1, "woe.scenemgr");
	if (pp==NULL)
	{
		return NULL;
	}
	else
	{
		return *pp;
	}
}

int getScene(lua_State* L)
{
	ISceneManager* pSceneMgr = getUserData(L);
	if (pSceneMgr)
	{
		int iid = luaL_checkint(L, 2);

		IScene* pScene = pSceneMgr->getScene(iid);
		if (pScene)
		{
			SceneLua::push(L, pScene);
			return 1;
		}
	}
	return 0;
}

int addScene(lua_State* L)
{
	if (lua_gettop(L)<5)
	{
		return 0;
	}

	ISceneManager* pSceneMgr = getUserData(L);
	if (pSceneMgr)
	{
		int cid = 0xff & luaL_checkint(L, 2);
		int did = 0xff & luaL_checkint(L, 3);
		int sid = 0xff & luaL_checkint(L, 4);

		short ntype = short(luaL_checkint(L, 5));

		int nStaticID = (cid<<24) | (did<<16) | (sid<<8); 
		if (nStaticID!=0)
		{
			IScene* pScene = pSceneMgr->addScene(nStaticID, ntype);
			if (pScene)
			{
				SceneLua::push(L, pScene);
				return 1;
			}
		}
	}
	return 0;
}

int rmvScene(lua_State* L)
{
	ISceneManager* pSceneMgr = getUserData(L);
	if (pSceneMgr)
	{
		int iid = luaL_checkint(L, 2);

		pSceneMgr->rmvScene(iid);
	}
	return 0;
}


static const luaL_Reg scene_mgr_funcs[] = {
	{"getScene", getScene},
	{"addScene", addScene},
	{"rmvScene", rmvScene},
	{NULL, NULL}
};


int libaray(lua_State* L)
{
	luaL_newmetatable(L, "woe.scenemgr");
	// fill member list into metatable
	luaL_register(L, NULL, scene_mgr_funcs);

	// metatable.__index = metatable
	lua_pushstring(L, "__index");
	lua_pushvalue(L, -2);
	lua_settable(L, -3);

	return 0;
}

} // end of scene lua
